package com.zone.gateway.core.authorization.auth;

import com.zone.gateway.core.authorization.GatewayAuthenticationToken;
import com.zone.gateway.core.authorization.IAuthService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author: zongzi
 * @description: 授权实现
 * @date: 2025/4/22
 */
public class AuthService implements IAuthService {
    private static final Logger logger = LoggerFactory.getLogger(AuthService.class);
    private static volatile SecurityManager securityManager;
    private final Subject subject;

    public AuthService() {
        // 确保SecurityManager只初始化一次
        if (securityManager == null) {
            synchronized (AuthService.class) {
                if (securityManager == null) {
                    initSecurityManager();
                }
            }
        }

        // 获取Subject
        subject = SecurityUtils.getSubject();
    }

    private void initSecurityManager() {
        try {
            // 1. 获取SecurityManager工厂，此处使用Ini配置文件初始化SecurityManager
            Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");

            // 2. 得到SecurityManager实例
            securityManager = factory.getInstance();

            // 3. 绑定给SecurityUtils
            SecurityUtils.setSecurityManager(securityManager);

            logger.info("SecurityManager初始化成功");
        } catch (Exception e) {
            logger.error("SecurityManager初始化失败", e);
            throw new RuntimeException("SecurityManager初始化失败", e);
        }
    }

    @Override
    public boolean validate(String id, String token) {
        try {
            subject.login(new GatewayAuthenticationToken(id, token));
            return subject.isAuthenticated();
        } finally {
            subject.logout();
        }
    }
}
